package InternetCode.Exa2;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 1）通过域名获得ip地址
 * 2）通过IP地址获得域名
 */
public class CoreCode {
    public static void main(String[] args) throws UnknownHostException {
        //通过域名获得ip地址
        String domain="www.baidu.com";
        InetAddress inetAddr=InetAddress.getByName(domain);
        System.out.println(domain+"对应ip为："+inetAddr.getHostAddress());

        //通过ip地址获得域名
        System.out.println("14.215.177.38对应的域名为: "+getCanonicalNameByIp("14.215.177.38"));
    }

    /**
     * 通过ip获得域名
     * @param ip
     * @return
     * @throws UnknownHostException
     */
    public static String getCanonicalNameByIp(String ip) throws UnknownHostException {
        String[] ipStr=ip.split("[.]");
        byte[] ipBytes=new byte[4];
        for(int i=0;i<4;i++){
            int m=Integer.parseInt(ipStr[i]);
            ipBytes[i]=(byte)(m&0xff);
        }
        InetAddress inetAddressByIp=InetAddress.getByAddress("8080",ipBytes);
        return inetAddressByIp.getCanonicalHostName();
    }
}
